<?php

namespace App\Http\Controllers\Customer;

use App\Exports\OrderCusExport;
use App\Exports\OrderExport;
use App\Http\Controllers\Controller;
use App\Http\Requests\Transport\OrderRequest;
use App\Imports\CusOrderImport;
use App\Imports\OrderImport;
use App\Models\airline\base\RouteModel;
use App\Models\base\AccountModel;
use App\Models\base\WarehouseModel;
use App\Models\client\PriceDetailModel;
use App\Models\CustomerChargeModel;
use App\Models\CustomerModel;
use App\Models\DictionaryModel;
use App\Models\OrderModel;
use App\Models\OrderReceiveModel;
use App\Models\TakeOrderModel;
use Barryvdh\DomPDF\Facade\Pdf;
use Dompdf\Dompdf;
use Dompdf\Options;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;
use Picqer\Barcode\BarcodeGeneratorPNG;

class Order extends Controller
{
    use OrderRequest;

    public function list(Request $request) {
        $page = $request->input('page', 1);
        $limit = $request->input('limit', 20);
        $auth = $request->get('auth');
        $keyword = $request->input('keyword', '');
        $goods_attr = $request->input('goods_attr', '');
        $des_country_id = $request->input('des_country_name', '');
        $destination = $request->input('des_country_name', '');
        $clearance_mode = $request->input('clearance_mode', '');
        $is_clearance = $request->input('is_clearance', '');
        $status = $request->input('status', '');
        $is_problem = $request->input('is_problem', '');
        $start_time = $request->input('startTime', '');
        $end_time = $request->input('endTime', '');
        $time_type = $request->input('time_type', '');
        $is_abnormal = $request->input('is_abnormal', '');

        $query = OrderModel::query()
            ->where('customer_id', $auth->id)
            ->where('is_child', 0)
            ->with([
                'create_admin', 'take_order_addr', 'customer', 'split_order_addr', 'take_order'
            ])->withCount('split_order_addr');

        if($keyword) {
            $take_order_find = TakeOrderModel::query()->where('sn', $keyword)->first();
            if($take_order_find){
                $query->where('take_order_id', $take_order_find->id);
            }else{
                $query->where('sn', $keyword);
            }

        }

        if($goods_attr){
            $query = $query->where('goods_attr', $goods_attr);
        }

        if($destination){
            $query = $query->where('destination', $destination);
        }

        if($clearance_mode){
            $query = $query->where('clearance_mode', $clearance_mode);
        }

        if(is_numeric($is_clearance)){
            $query = $query->where('is_clearance', intval($is_clearance));
        }

        if($status){
            $query = $query->where('status', $status);
        }

        if(is_numeric($is_problem)){
            $query = $query->where('is_issue', intval($is_problem));
        }

        if(is_numeric($is_abnormal)){
            $query = $query->where('is_exception', intval($is_abnormal));
        }

        // 时间类型（预报-pre，确认-confirm，预报出货-pre_out，入库-storage，出库-outstock，抵达-arrive，清关-clearance，签收-signed）
        if($time_type && $start_time && $end_time) {
            switch ($time_type){
                case 'pre':
                    $query->whereBetween('pre_time', [$start_time, $end_time]);
                    break;
                case 'confirm':
                    $query->whereBetween('confirm_time', [$start_time, $end_time]);
                    break;
                case 'pre_out':
                    $query->whereBetween('pre_out_date', [$start_time, $end_time]);
                    break;
                case 'storage':
                    $query->whereBetween('storage_time', [$start_time, $end_time]);
                    break;
                case 'outstock':
                    $query->whereBetween('outstock_time', [$start_time, $end_time]);
                    break;
                case 'arrive':
                    $query->whereBetween('arrive_time', [$start_time, $end_time]);
                    break;
                case 'clearance':
                    $query->whereBetween('clearance_time', [$start_time, $end_time]);
                    break;
                case 'signed':
                    $query->whereBetween('signed_time', [$start_time, $end_time]);
                    break;
                default:
                    break;
            }
        }


        $total = $query->count('id');
        $items = $query
            ->offset(($page-1) * $limit)
            ->limit($limit)
            ->orderBy('id', 'desc')
            ->get();


        $list = $items->map(function($item) {
            $customer = $item->customer;
            $take_order = $item->take_order;
            $take_order_addr = [
                'addr' => $item->take_order_addr ? $item->take_order_addr->addr : '',
                'goods_name' => $item->take_order_addr ? $item->take_order_addr->goods_name : '',
                'remark' => $item->take_order_addr ? $item->take_order_addr->remark : ''
            ];
            $split_order_addr = $item->split_order_addr->map(function($item2) {
                return [
                    'addr' => $item2->addr,
                    'nums' => $item2->nums,
                    'weight' => $item2->weight,
                    'goods_name' => $item2->goods_name,
                    'remark' => $item2->remark,
                ];
            });

            $packages_name = DictionaryModel::whereIn('id', explode(',', $item->packages))
                ->pluck('name');

            $entry_mode_name = DictionaryModel::where('id', $item->entry_mode)->value('name');

            $take_order_sn = $take_order && $take_order->show_sn == 2 ? $take_order->sn : '';

            $flight_info = $take_order && $take_order->flight_info_show == 1 ? $take_order->flight_info :  '';

            $grass_files = $take_order && $take_order->grass_files ? json_decode($take_order->grass_files,  true) :  [];
            $final_files = $take_order && $take_order->final_files ? json_decode($take_order->final_files,  true) :  [];


            $res = [
                'id' => $item->id,
//                'airport_id' => $item->airport_id,
                'destination' => $item->destination,
                'customer_id' => $item->customer_id,
                'customer_name' => $customer ? $customer->name : '',
                'customer_sn' => $customer ? $customer->sn : '',
                'customer_type' => ($customer && $customer->customer_type) ? $customer->customer_type->name : '',
                'sn' => $item->sn,
                'take_order_sn' => $take_order_sn,
                'split_order_addr' => $item->split_order_addr_count,
                'status' => $item->customer_status,
                'status_name' => OrderModel::STATUS_MAPS[$item->customer_status] ?? '',
                'big_pkgs' => $item->big_pkgs,
                'storage_big_pkgs' => $item->storage_big_pkgs,
                'pre_out_date' => $item->pre_out_date,
//                'des_country_id' => $item->des_country_id,
//                'des_city_id' => $item->des_city_id,
//                'des_country_name' => $item->airport->country_name ?? '',
                'goods_attr' => $item->goods_attr,
                'goods_attr_name' => OrderModel::GOODS_ATTR_MAPS[$item->goods_attr] ?? '',
                'clearance_mode' => $item->clearance_mode,
                'clearance_mode_name' => OrderModel::CLEARANCE_MODE_MAPS[$item->clearance_mode] ?? '',
                'is_clearance' => $item->is_clearance,
                'pre_weight' => $item->pre_weight,
                'pre_volume' => $item->pre_volume,
                'pre_volume_weight' => round($item->pre_volume * 166.67, 2),
                'volume_ratio' => round($item->pre_weight != 0 ? ($item->pre_volume * 166.67) / $item->pre_weight : 0, 2),
                'storage_weight' => $item->storage_weight,
                'storage_volume' => $item->storage_volume,
                'packages' => array_filter(explode(',', $item->packages)),
                'packages_name' => $packages_name,
                'pre_time' => $item->pre_time,
                'confirm_time' => $item->confirm_time,
                'storage_time' => $item->storage_time,
                'outstock_time' => $item->outstock_time,
                'arrive_time' => $item->arrive_time,
                'clearance_time' => $item->clearance_time,
                'signed_time' => $item->signed_time,
                'is_issue' => $item->is_issue,
                'is_exception' => $item->is_exception,
                'take_order' => $take_order_addr,
                'split_order' => $split_order_addr,
                'entry_mode' => $item->entry_mode,
                'ship_info' => $item->ship_info,
                'bubble_weight' => $item->bubble_weight,
                'clearance_list' => $item->clearance_list,
                'rule1' => $item->rule1,
                'rule2' => $item->rule2,
                'small_pkgs' => $item->small_pkgs,
                'entry_mode_name' => $entry_mode_name,
                'flight_info' => $flight_info,
                'grass_files' => $grass_files,
                'final_files' => $final_files,
            ];
            return $res;
        });

        return $this->success(['list' => $list, 'total' => $total]);
    }

    //预报下单
    public function preorder(Request $request){
        $auth = $request->get('auth');
        $params = $request->all();
        $id = intval($request->input('id', 0));

        $check_res = self::preorder_check($params);
        if($check_res->faild){
            return $this->error($check_res->err);
        }

        if(!$params['destination']){
            return $this->error('请选择目的地');
        }

        if($id) {
            $model = OrderModel::find($id);
            if(!$model) {
                return $this->error('入仓单不存在');
            }

            //只有预报状态能编辑
            if($model->status != OrderModel::STATUS_PREORDER) {
                return $this->error('只有预报状态能编辑');
            }

             $take_order = $model->take_order_addr;
        } else {
            $model = new OrderModel();
            $model->sn = trim($params['rule1']??'') . trim($params['rule2']??'') . date('ymd') . get_order_sn() . trim($params['suffix']??'');
            $model->rule1 = $params['rule1'] ?? '';
            $model->rule2 = $params['rule2'] ?? '';
            $model->status = OrderModel::STATUS_PREORDER;
            $model->customer_status = OrderModel::STATUS_PREORDER;
            $model->pre_time = date('Y-m-d H:i:s');

             $take_order = new OrderReceiveModel();
        }

        DB::beginTransaction();
        try {
            $model->customer_id = $auth->id;
//            $model->airport_id = $params['airport_id'];
            $model->destination = $params['destination'];
            $model->goods_attr = $params['goods_attr'];
            $model->clearance_mode = $params['clearance_mode'];
            $model->entry_mode = $params['entry_mode'];
            $model->surplus_weight = floatval($params['pre_weight'] ?? 0);
            $model->pre_weight = floatval($params['pre_weight'] ?? 0);
            $model->pre_volume = floatval($params['pre_volume'] ?? 0);
            $model->is_clearance = intval($params['is_clearance'] ?? 0);
            $model->bubble_weight = floatval($params['bubble_weight'] ?? 0);
            $model->pre_out_date = $params['pre_out_date'] ?? null;
            $model->big_pkgs = intval($params['big_pkgs'] ?? 0);
            $model->load_pkgs_surplus = intval($params['big_pkgs'] ?? 0);
            $model->small_pkgs = intval($params['small_pkgs'] ?? 0);
            $model->packages = implode(',',$params['packages'] ?? []);
            $model->loadless_big_pkgs = intval($params['big_pkgs'] ?? 0);
            $model->ship_info = $params['ship_info'] ?? '';
            $model->clearance_list = $params['clearance_list'];
            $model->created_admin_id = 0;
            $model->save();

            if($params['take_order']['addr'] != ''){
                $take_order->weight = 0;
                $take_order->nums = 0;
                $take_order->order_id = $model->id;
                $take_order->type = OrderReceiveModel::TAKE_TYPE;
                $take_order->addr = $params['take_order']['addr'];
                $take_order->goods_name = $params['take_order']['goods_name'];
                $take_order->remark = $params['take_order']['remark'] ?? '';
                $take_order->save();
            }

            OrderReceiveModel::where('order_id', $model->id)
                ->where('type', OrderReceiveModel::SPLIT_TYPE)
                ->delete();
            if(isset($params['split_order'])) {
                foreach($params['split_order'] as $item) {
                    $split_order = new OrderReceiveModel();
                    $split_order->weight = $item['weight'];
                    $split_order->nums = $item['nums'];
                    $split_order->order_id = $model->id;
                    $split_order->type = OrderReceiveModel::SPLIT_TYPE;
                    $split_order->addr = $item['addr'];
                    $split_order->goods_name = $item['goods_name'];
                    $split_order->remark = $item['remark'] ?? '';
                    $split_order->save();
                }
            }

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->error($e->getMessage());
        }

        return $this->success();
    }

    //确认下单
    public function confirm(Request $request){
        $auth = $request->get('auth');
        $params = $request->all();
        $id = intval($request->input('id'));

        $check_res = self::confirm_check($params);
        if($check_res->faild){
            return $this->error($check_res->err);
        }

        if(!isset($params['destination'])){
            return $this->error('请选择目的地');
        }

        if($id) {
            //有预报的单
            $order = OrderModel::find($id);
            if(!$order) {
                return $this->error('入仓单不存在');
            }
            //只有预报状态能确认
            if($order->status != OrderModel::STATUS_PREORDER) {
                return $this->error('只有预报状态能确认');
            }

        } else {
            //新单确认
            $order = new OrderModel();
            $order->sn = trim($params['rule1']??'') . trim($params['rule2']??'') . date('ymd') . get_order_sn() . trim($params['suffix']??'');
            $order->rule1 = $params['rule1'] ?? '';
            $order->rule2 = $params['rule2'] ?? '';
        }

        $take_order = $order->take_order_addr;
        if(!$take_order) {
            $take_order = new OrderReceiveModel();
        }


        DB::beginTransaction();
        try {
            $order->status = OrderModel::STATUS_CONFIRM;
            $order->customer_status = OrderModel::STATUS_CONFIRM;
            $order->confirm_time = date('Y-m-d H:i:s');
            $order->surplus_weight = floatval($params['pre_weight'] ?? 0);
            $order->customer_id = $auth->id;
//            $order->airport_id = $params['airport_id'];
            $order->destination = $params['destination'] ?? '';
            $order->goods_attr = $params['goods_attr'];
            $order->clearance_mode = $params['clearance_mode'];
            $order->entry_mode = $params['entry_mode'];
            $order->pre_weight = floatval($params['pre_weight'] ?? 0);
            $order->pre_volume = floatval($params['pre_volume'] ?? 0);
            $order->is_clearance = intval($params['is_clearance'] ?? 0);
            $order->bubble_weight = floatval($params['bubble_weight'] ?? 0);
            $order->pre_out_date = $params['pre_out_date'] ?? null;
            $order->big_pkgs = intval($params['big_pkgs'] ?? 0);
            $order->small_pkgs = intval($params['small_pkgs'] ?? 0);
            $order->packages = implode(',',$params['packages'] ?? []);
            $order->load_pkgs_surplus = intval($params['big_pkgs'] ?? 0);
            $order->loadless_big_pkgs = intval($params['big_pkgs'] ?? 0);
            $order->ship_info = $params['ship_info'] ?? '';
            $order->clearance_list = $params['clearance_list'];
            $order->created_admin_id = 0;
            $order->save();


            //提单
            $take_order->weight = 0;
            $take_order->nums = 0;
            $take_order->order_id = $order->id;
            $take_order->type = OrderReceiveModel::TAKE_TYPE;
            $take_order->addr = $params['take_order']['addr'];
            $take_order->goods_name = $params['take_order']['goods_name'];
            $take_order->remark = $params['take_order']['remark'] ?? '';
            $take_order->save();

            //分单
            OrderReceiveModel::where('order_id', $order->id)
                ->where('type', OrderReceiveModel::SPLIT_TYPE)
                ->delete();
            if(isset($params['split_order'])) {
                foreach($params['split_order'] as $item) {
                    $split_order = new OrderReceiveModel();
                    $split_order->weight = $item['weight'];
                    $split_order->nums = $item['nums'];
                    $split_order->order_id = $order->id;
                    $split_order->type = OrderReceiveModel::SPLIT_TYPE;
                    $split_order->addr = $item['addr'];
                    $split_order->goods_name = $item['goods_name'];
                    $split_order->remark = $item['remark'] ?? '';
                    $split_order->save();
                }
            }

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->error($e->getMessage());
        }

        return $this->success();
    }

    //详情
    public function detail(Request $request, int $id){
        $auth = $request->get('auth');
        $order = OrderModel::withCount('split_order_addr')
            ->with([
                'split_order_addr'
            ])
            ->where('customer_id', $auth->id)
            ->find($id);
        if(!$order) {
            return $this->error('记录不存在');
        }

        $take_receive = OrderReceiveModel::where('order_id', $order->id)
            ->where('type', OrderReceiveModel::TAKE_TYPE)
            ->first();

        $packages_name = DictionaryModel::whereIn('id', explode(',', $order->packages))
            ->pluck('name');

        $entry_mode_name = DictionaryModel::where('id', $order->entry_mode)->value('name');
        $res = [
            'id' => $order->id,
            'sn' => $order->sn,
            'take_order_no' => $order->take_order->sn ?? '',
            'pre_weight' => $order->pre_weight,
            'storage_weight' => $order->storage_weight,
            'split_order_addr_count' => $order->split_order_addr_count ?? 0,
            'status' => OrderModel::STATUS_MAPS[$order->status] ?? '',
            'pre_out_date' => $order->pre_out_date,
            'is_clearance' => $order->is_clearance,
            'des_city' => $order->des_city->name ?? '',
            'des_country' => $item->airport->country_name ?? '',
            'goods_attr' => OrderModel::GOODS_ATTR_MAPS[$order->goods_attr] ?? '',
            'clearance_mode' => OrderModel::CLEARANCE_MODE_MAPS[$order->clearance_mode] ?? '',
            'pre_volume' => $order->pre_volume,
            'storage_volume' => $order->storage_volume,
            'packages' => $packages_name,
            'storage_big_pkgs' => $order->storage_big_pkgs,
            'big_pkgs' => $order->big_pkgs,
            'small_pkgs' => $order->small_pkgs,
            'pre_time' => $order->pre_time,
            'confirm_time' => $order->confirm_time,
            'storage_time' => $order->storage_time,
            'outstock_time' => $order->outstock_time,
            'arrive_time' => $order->arrive_time,
            'signed_time' => $order->signed_time,
            'take_receive' => $take_receive,
            'split_order' => $order->split_order_addr ?? [],
            'entry_mode' => $entry_mode_name,
        ];

        return $this->success($res);
    }

    public function delete(int $id){
        $model = AccountModel::find($id);
        if(!$model) {
            return $this->error('记录不存在');
        }
        $model->delete();
        return $this->success();
    }

    public function price_query(Request $request)
    {
        $auth = $request->get('auth');
        $weight = $request->input('weight', 0);
        $destination = $request->input('destination', 0);
        $goods_attr = $request->input('goods_attr', 0);
        if(!$weight){
            return $this->error('请输入重量');
        }

        if(!$destination){
           return $this->error('请选择目的地');
        }

        $route_ids = RouteModel::where('arrive_port_code', $destination)->pluck('id');

        if(!$goods_attr){
            return $this->error('请选择货物属性');
        }

        $find_price = PriceDetailModel::where('customer_id', $auth->id)
            ->whereIn('route_id', $route_ids)
            ->where('goods_attr', $goods_attr)
            ->first();

        $cost = 0;
        if($find_price){
            $price = 0;
            if($weight >= 1000){
                $price = $find_price->price1000 ?? 0;
            }elseif($weight >= 500){
                $price = $find_price->price500 ?? 0;
            }elseif ($weight >= 300){
                $price = $find_price->price300 ?? 0;
            }elseif ($weight >= 100){
                $price = $find_price->price100 ?? 0;
            }elseif($weight >= 45){
                $price = $find_price->price45 ?? 0;
            }

            $cost = round($price * $weight, 2);
        }else{
            return $this->error('暂无计费规则');
        }

        return $this->success(['transport_cost' => $cost]);
    }

    public function warehouse(Request $request)
    {
        $list = WarehouseModel::select('id', 'name')->get();
        return $this->success($list);
    }

    /**
     * Notes:取消异常
     * User: xiangzi
     * Date: 2025/5/6
     * Time: 下午6:37
     * @return \Illuminate\Http\JsonResponse
     */
    public function abnormal_cancel(Request $request)
    {
        $ids = $request->input('id', '');
        $ids = explode(',', $ids);

        DB::beginTransaction();
        try {
            foreach ($ids as $id) {
                $find_order = OrderModel::find($id);

                $find_order->is_exception = 0;
                $find_order->save();
            }
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->error($e->getMessage());
        }

        return $this->success();
    }


//    public function export(Request $request){
//        $ids = $request->input('ids', []);
//        if(empty($ids)){
//            return $this->error('请选择要导出的数据');
//        }
//
//        $query = OrderModel::query()->with(['take_order', 'customer', 'airport']);
//        $query->whereIn('id', $ids);
//        $items = $query
//            ->orderBy('id', 'desc')
//            ->get();
//
//        $list = $items->map(function($item) {
//            $res = [
//                'sn' => $item->customer->name ?? '',
//                'take_order_sn' => $item->take_order->sn ?? '',
//                'split_order_addr' => $item->split_order_addr_count,
//                'status' => OrderModel::STATUS_MAPS[$item->status] ?? '',
//                'big_pkgs' => $item->big_pkgs,
//                'pre_out_date' => $item->pre_out_date,
//                'des_country_name' => $item->airport->country_name ?? '',
//                'goods_attr_name' => OrderModel::GOODS_ATTR_MAPS[$item->goods_attr] ?? '',
//                'clearance_mode_name' => OrderModel::CLEARANCE_MODE_MAPS[$item->clearance_mode] ?? '',
//                'pre_weight' => $item->pre_weight,
//                'pre_volume' => $item->pre_volume,
//            ];
//            return $res;
//        });
//
//        $file_name = '入仓单列表-'.date('Ymd').'.xlsx';
//        return Excel::download(new ProblemExport($list), $file_name);
//    }


    public function export(Request $request){
//        $keyword = $request->input('keyword', '');
//        $goods_attr = $request->input('goods_attr', '');
//        $des_country_id = $request->input('des_country_name', '');
//        $clearance_mode = $request->input('clearance_mode', '');
//        $customer_type_id = $request->input('customer_type', '');
//        $is_clearance = $request->input('is_clearance', '');
//        $status = $request->input('status', '');
//        $is_problem = $request->input('is_problem', '');
//        $is_abnormal = $request->input('is_abnormal', '');
//
//        $time_type = $request->input('time_type', '');
//        $start_time = $request->input('startTime', '');
//        $end_time = $request->input('endTime', '');
//
//        $query = OrderModel::query()
//            ->with([
//                'create_admin', 'take_order_addr', 'customer', 'split_order_addr', 'take_order'
//            ])->withCount('split_order_addr');
//
//        if($keyword) {
//            $query->where('sn', 'like', "%{$keyword}%");
//        }
//
//        if($customer_type_id) {
//            $query->whereIn('customer_id', function($query) use ($customer_type_id) {
//                $query->select('id')->from((new CustomerModel())->getTable())->where('customer_type_id', $customer_type_id);
//            });
//        }
//
//        if($goods_attr){
//            $query = $query->where('goods_attr', $goods_attr);
//        }
//
//        if($des_country_id){
//            $query = $query->where('des_country_id', $des_country_id);
//        }
//
//        if($clearance_mode){
//            $query = $query->where('clearance_mode', $clearance_mode);
//        }
//
//        if(is_numeric($is_clearance)){
//            $query = $query->where('is_clearance', intval($is_clearance));
//        }
//
//        if($status){
//            $query = $query->where('status', $status);
//        }
//
//        if(is_numeric($is_problem)){
//            $query = $query->where('is_issue', intval($is_problem));
//        }
//
//        if(is_numeric($is_abnormal)){
//            $query = $query->where('is_exception', intval($is_abnormal));
//        }
//        // 时间类型（预报-pre，确认-confirm，预报出货-pre_out，入库-storage，出库-outstock，抵达-arrive，清关-clearance，签收-signed）
//        if($time_type && $start_time && $end_time) {
//            switch ($time_type){
//                case 'pre':
//                    $query->whereBetween('pre_time', [$start_time, $end_time]);
//                    break;
//                case 'confirm':
//                    $query->whereBetween('confirm_time', [$start_time, $end_time]);
//                    break;
//                case 'pre_out':
//                    $query->whereBetween('pre_out_date', [$start_time, $end_time]);
//                    break;
//                case 'storage':
//                    $query->whereBetween('storage_time', [$start_time, $end_time]);
//                    break;
//                case 'outstock':
//                    $query->whereBetween('outstock_time', [$start_time, $end_time]);
//                    break;
//                case 'arrive':
//                    $query->whereBetween('arrive_time', [$start_time, $end_time]);
//                    break;
//                case 'clearance':
//                    $query->whereBetween('clearance_time', [$start_time, $end_time]);
//                    break;
//                case 'signed':
//                    $query->whereBetween('signed_time', [$start_time, $end_time]);
//                    break;
//                default:
//                    break;
//            }
//        }
//
//        $items = $query
//            ->orderBy('id', 'desc')
//            ->get();


        $ids = $request->get('ids',  []);
        $items = OrderModel::with(['take_order'])->whereIn('id', $ids)->get();

        $list = $items->map(function($item) {
            $packages_name = DictionaryModel::whereIn('id', explode(',', $item->packages))
                ->pluck('name')->implode('+');

            $entry_mode_name = DictionaryModel::where('id', $item->entry_mode)->value('name');

            $volume_ratio = $item->bubble_weight ?? 0;
            $res = [
                'sn' => $item->sn,
                'take_order_sn' => $item->take_order->sn ?? '',
                'status_name' => OrderModel::STATUS_MAPS[$item->status] ?? '',
                'big_pkgs' => $item->big_pkgs,
                'small_pkgs' => $item->small_pkgs,
                'packages_name' => $packages_name,
                'pre_out_date' => $item->pre_out_date,
                'des_country_name' => $item->destination,
                'goods_attr_name' => OrderModel::GOODS_ATTR_MAPS[$item->goods_attr] ?? '',
                'clearance_mode_name' => OrderModel::CLEARANCE_MODE_MAPS[$item->clearance_mode] ?? '',
                'is_clearance' => $item->is_clearance == 0 ? '否' : '是',
                'pre_weight' => $item->pre_weight,
                'pre_volume' => $item->pre_volume,
                'volume_ratio' => $volume_ratio,
                'entry_mode_name' => $entry_mode_name,
//                'storage_weight' => $item->storage_weight,
//                'storage_volume' => $item->storage_volume,
//                'warehouse' => $item->place?->warehouse?->name ?? '',
//                'pre_volume_weight' => $item->pre_volume * 167,
//                'ratio_weight' => $volume_ratio * $item->pre_weight,
//                'packages_name' => $packages_name,
//                'pre_time' => $item->pre_time,
//                'confirm_time' => $item->confirm_time,
//                'storage_time' => $item->storage_time,
//                'outstock_time' => $item->outstock_time,
//                'arrive_time' => $item->arrive_time,
//                'clearance_time' => $item->clearance_time,
//                'signed_time' => $item->signed_time,
            ];
            return $res;
        });

        return Excel::download(new OrderCusExport(collect($list)), '入仓单.xlsx');
    }


    //导入
    public function import(Request $request) {
        $auth = $request->get('auth');
        $file = $request->file('file');
        if(!$file) {
            return $this->error('请选择文件');
        }

        $import = new CusOrderImport();
        Excel::import($import, $file);

        if(!empty($import->error)) {
            return $this->success([
                'errors' => $import->error
            ]);
        }

        DB::beginTransaction();
        try {
            foreach($import->result as $params) {
                $customer = CustomerModel::find($auth->id);

                $model = new OrderModel();
                $model->sn = ($customer->name_en ?? '') . $params['destination'] . date('ymd') . get_order_sn();
                $model->status = OrderModel::STATUS_PREORDER;
                $model->pre_time = date('Y-m-d H:i:s');

                $model->customer_id = $customer->id;
                $model->destination = $params['destination'];
                $model->goods_attr = $params['goods_attr'];
                $model->clearance_mode = $params['clearance_mode'];
                $model->entry_mode = $params['entry_mode'];
                $model->pre_weight = floatval($params['pre_weight'] ?? 0);
                $model->pre_volume = floatval($params['pre_volume'] ?? 0);
                $model->is_clearance = intval($params['is_clearance'] ?? 0);
                $model->bubble_weight = floatval($params['bubble_weight'] ?? 0);
                $model->pre_out_date = $params['pre_out_date'] ?? null;
                $model->big_pkgs = intval($params['big_pkgs'] ?? 0);
                $model->small_pkgs = intval($params['small_pkgs'] ?? 0);
                $model->packages = implode(',', $params['packages'] ?? []);

                $model->load_pkgs_surplus = intval($params['big_pkgs'] ?? 0);
                $model->loadless_big_pkgs = intval($params['big_pkgs'] ?? 0);

                $model->save();

                $take_order = new OrderReceiveModel();
                $take_order->weight = $model->pre_weight;
                $take_order->nums = $model->big_pkgs;
                $take_order->order_id = $model->id;
                $take_order->type = OrderReceiveModel::TAKE_TYPE;
                $take_order->addr = $params['address'];
                $take_order->goods_name = $params['goods_name'];
                $take_order->save();


            }
            DB::commit();
        } catch(\Exception $e) {
            DB::rollBack();
            return $this->error($e->getMessage());
        }

        return $this->success();

    }


    public function pdf(Request $request)
    {
        $ids = $request->input('ids', []);
        if(empty($ids)){
            return $this->error('请选择要导出的数据');
        }

        $query = OrderModel::whereIn('id', $ids)->get();
//        $query = OrderModel::whereIn('id', [30])->get();

        $list = $query->map(function($item) {
            return [
                'sn' => $item->sn,
                'big_pkgs' => $item->big_pkgs,
            ];
        });

        // 生成每个条形码的 base64 数据
        $generator = new BarcodeGeneratorPNG();

        $data = [];

        $content = '';
        foreach ($list as $item){
            $data[] = [
                'sn' => $item['sn'],
                'num' => $item['big_pkgs'],
                'barcode' => base64_encode($generator->getBarcode($item['sn'], $generator::TYPE_CODE_128)),
            ];

            $barcode = base64_encode($generator->getBarcode($item['sn'], $generator::TYPE_CODE_128));

            $content .= '<div class="barcode-item">
                <img src="data:image/png;base64,'.$barcode.'" alt="条形码 '.$item['sn'].'">
                <p>Order No: '.$item['sn'].'</p>
                <p>Nums: '.$item['big_pkgs'].'</p>
            </div>';
        }


        $html = '<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>入仓面单</title>
    <style>
    body { font-family: "simsunb", sans-serif; }
        .barcode-item {
            margin-bottom: 30px;
        }
    </style>
</head>
<body>

'.$content.'
</body>
</html>';



        $options = new Options();

//        $options->set('simsunb', 'Courier');
//        var_dump($options->get('fontDir'));exit();
//        $options->set('fontDir', resource_path('fonts'));
//        $options->set('fontCache', resource_path('fonts'));
//        $options->set('tempDir', storage_path('app/dompdf'));

        $dompdf = new Dompdf($options);
        $dompdf->loadHtml($html);
        $dompdf->setPaper('A4', 'portrait');
        $dompdf->render();

        $dompdf->stream("miandan.pdf");

    }


    public function pdf_test(Request $request) {
        $query = OrderModel::whereIn('id', [30])->get();


        $list = $query->map(function($item) {
            return [
                'sn' => $item->sn,
                'big_pkgs' => $item->big_pkgs,
            ];
        });

        // 生成每个条形码的 base64 数据
        $generator = new BarcodeGeneratorPNG();

        $data = [];
        foreach ($list as $item){
            $data['data'][] = [
                'sn' => $item['sn'],
                'num' => $item['big_pkgs'],
                'barcode' => base64_encode($generator->getBarcode($item['sn'], $generator::TYPE_CODE_128)),
            ];
        }

        // 加载视图并生成 PDF
        $pdf = Pdf::loadView('pdf.miandan', $data)
            ->setOptions([
                'isRemoteEnabled' => true,
                'defaultFont' => 'SimHei',
                'fontDir' => resource_path('fonts'),
                'fontCache' => resource_path('fonts'),
                'tempDir' => storage_path('app/dompdf'),
            ]);


        // 下载 PDF
        return $pdf->download('example.pdf');



    }

}
